package com.zhu.es.service;


import com.alibaba.fastjson.JSON;
import com.zhu.es.config.ElasticsearchConfig;
import com.zhu.es.pojo.Content;
import com.zhu.es.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentService {

    @Autowired
    @Qualifier("esRestClient")
    private RestHighLevelClient client;

    //解析数据放入es索引中
    public Boolean parseContent(String keyword) throws IOException {
        List<Content> contents = new HtmlParseUtil().parseJD(keyword);
        //把查询到的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        //循环把获取到的数据遍历存进es索引中
        for (int i = 0; i < contents.size(); i++) {
            IndexRequest indexRequest = new IndexRequest("jd_goods");
            indexRequest.source(JSON.toJSONString(contents.get(i)), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        return !bulk.hasFailures();
    }

    //获取这些es的数据，实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNum,int pageSize) throws IOException {
        if(pageNum <= 1){
            pageNum = 1;
        }

        //搜索请求
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        //条件构造
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        //搜索条件
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);

        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        //遍历所有获取的结果
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //把遍历的所有结果放进list中返回
            list.add(sourceAsMap);
        }
        return list;
    }

    //获取这些es的数据，实现搜索功能。（多了个高亮关键字功能）
    public List<Map<String,Object>> searchHighlightPage(String keyword,int pageNum,int pageSize) throws IOException {
        if(pageNum <= 1){
            pageNum = 1;
        }

        //搜索请求
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        //条件构造
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        //搜索条件
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮关键字
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title"); //设置高亮的字段
        highlightBuilder.requireFieldMatch(false); //多个高亮设置显示
        highlightBuilder.preTags("<span style='color:red'>"); //设置高亮的样式
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);

        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        //遍历所有获取的结果
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            //获取高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //原来没有高亮字段的结果
            //解析高亮的字段，将原来的字段替换为高亮的字段
            if(title != null){
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title",n_title); //高亮字段替换原来的字段
            }
            //把遍历的所有结果放进list中返回
            list.add(sourceAsMap);
        }
        return list;
    }
}
